package com.anpxd.erpad.ui

import android.annotation.SuppressLint
import android.support.v4.content.ContextCompat
import android.support.v7.widget.DividerItemDecoration
import android.support.v7.widget.LinearLayoutManager
import android.support.v7.widget.RecyclerView
import android.view.View
import android.widget.TextView
import com.anpxd.erpad.R
import com.anpxd.erpad.adapter.BrandAdapter
import com.anpxd.erpad.adapter.SeriesAdapter
import com.anpxd.erpad.bean.*
import com.anpxd.erpad.net.ApiFactory
import com.anpxd.erpad.net.ErpApi
import com.anpxd.erpad.utils.BackHomeTimer
import com.anpxd.ewalker.utils.GsonUtil
import com.chad.library.adapter.base.BaseQuickAdapter
import com.gg.baseproject.Composers
import com.jiajie.load.LoadingDialog
import com.lsxiao.apollo.core.Apollo
import com.socks.library.KLog
import io.reactivex.android.schedulers.AndroidSchedulers
import io.reactivex.schedulers.Schedulers
import kotlinx.android.synthetic.main.fragment_sort.*
import kotlinx.android.synthetic.main.fragment_sort.view.*


/**
 * Creator : GG
 * Date    : 2018/2/8
 * Mail    : gg.jin.yu@gmai.com
 * Explain :
 */
class SortActivity : BaseActivity(), LetterSideBar.OnTouchLetterListener {

    companion object {
        const val KEY_DATA = "data"
    }

    private val data: ArrayList<BrandItem> = arrayListOf()

    private val mBrandAdapter = BrandAdapter(data = data)

    private val mSeriesAdapter = SeriesAdapter()

    private val loadDialog: LoadingDialog by lazy { LoadingDialog.Builder(this).canceledOnTouchOutside(false).build() }


    private val mSeriesManager by lazy { LinearLayoutManager(this) }
    private val mBrandManager by lazy { LinearLayoutManager(this) }

    private val mSearch: Search by lazy {
        GsonUtil.jsonToBean(intent.getStringExtra(KEY_DATA), Search::class.java) ?: Search()
    }

    private lateinit var title: TextView

    private var mBrandPosition: Int = 0

    private var mSeriesPosition: Int = 0

    private val mDecoration: DividerItemDecoration by lazy {
        DividerItemDecoration(this, DividerItemDecoration.VERTICAL).apply {
            setDrawable(ContextCompat.getDrawable(this@SortActivity, R.drawable.divider_ll_grey_h)!!)
        }
    }

    override fun getLayoutRes(): Int = R.layout.fragment_sort

    override fun initArguments() {
        KLog.w("search", mSearch)
    }

    override fun initTitle() {
        back.setOnClickListener {
            finish()
        }
        confirm.setOnClickListener {
            Apollo.emit(BusTag.search, mSearch)
            finish()
        }

    }

    override fun initView() {
        letterSideBar.setOnTouchLetterListener(this)
        initBrand()
        initSeries()
        initOther()
    }


    override fun initData() {
        initBrandData()
        initSeriesData()

        mileage_choose.setRange(mSearch.fromMileageIndex?: 0, mSearch.toMileageIndex ?: resources.getStringArray(R.array.mileage_array).count() - 1)
        car_age_choose.setRange(mSearch.fromCarAgeIndex?: 0, mSearch.toCarAgeIndex?: resources.getStringArray(R.array.car_age_array).count() - 1)
        price_rangeBar.setRange(mSearch.fromRetailPriceIndex?: 0, mSearch.toRetailPriceIndex?: resources.getStringArray(R.array.price_array).count() - 1)
    }


    private fun initSeries() {

        seriesRecyclerView.layoutManager = mSeriesManager

        seriesRecyclerView.addItemDecoration(mDecoration)

        seriesRecyclerView.adapter = mSeriesAdapter

        seriesRecyclerView.addOnScrollListener(object : RecyclerView.OnScrollListener() {

            override fun onScrolled(recyclerView: RecyclerView?, dx: Int, dy: Int) {
                super.onScrolled(recyclerView, dx, dy)
                BackHomeTimer.getInstance().resetTime()
            }
        })

        mSeriesAdapter.onItemClickListener = BaseQuickAdapter.OnItemClickListener { _, _, position ->

            if (position > mSeriesAdapter.data.size - 1) {
                return@OnItemClickListener
            }
            mSeriesAdapter.data[mSeriesPosition].choose = false
            mSeriesAdapter.notifyItemChanged(mSeriesPosition)
            mSeriesAdapter.data[position].choose = true
            mSeriesAdapter.notifyItemChanged(position)
            mSeriesPosition = position
            mSearch.seriesId = mSeriesAdapter.data[position].seriesId

            BackHomeTimer.getInstance().resetTime()
        }

    }

    private fun initSeriesData() {
        if (mSearch.brandId == 0) {
            mSeriesAdapter.setNewData(null)
            mSearch.seriesId = 0
        } else
            ApiFactory.getErpApi()
                    .series(brandId = mSearch.brandId)
                    .compose(Composers.handleError())
                    .subscribe({
                        it.add(0, Series(seriesName = "不限车系", seriesId = null))
                        it.forEach {
                            if (it.seriesId == mSearch.seriesId)
                                it.choose = true
                        }
                        mSeriesAdapter.setNewData(it)
                    }, {})
    }

    private fun initBrand() {

        title = findViewById(R.id.title_text)!!

        brandRecyclerView.addItemDecoration(mDecoration)

        brandRecyclerView.layoutManager = mBrandManager

        brandRecyclerView.adapter = mBrandAdapter


        var height = 0
        var mCurrentPosition = 0
        brandRecyclerView.addOnScrollListener(object : RecyclerView.OnScrollListener() {
            override fun onScrollStateChanged(recyclerView: RecyclerView?, newState: Int) {
                super.onScrollStateChanged(recyclerView, newState)
                height = header.height
            }

            override fun onScrolled(recyclerView: RecyclerView?, dx: Int, dy: Int) {
                super.onScrolled(recyclerView, dx, dy)
                BackHomeTimer.getInstance().resetTime()
                if (mBrandAdapter.getItemViewType(mCurrentPosition + 1) == BrandItem.TITLE) {
                    val view = mBrandManager.findViewByPosition(mCurrentPosition + 1)
                    if (view != null) {
                        if (view.top <= height) {
                            header.y = (view.top - height).toFloat()
                        } else {
                            header.y = 0f
                        }
                    }
                }

                if (mCurrentPosition != mBrandManager.findFirstVisibleItemPosition()) {
                    mCurrentPosition = mBrandManager.findFirstVisibleItemPosition()

                    if (dy > 0 && mBrandAdapter.getItemViewType(mCurrentPosition + 1) != BrandItem.TITLE) {
                        header.y = 0f
                    } else if (dy < 0 && mBrandAdapter.getItemViewType(mCurrentPosition + 1) == BrandItem.TITLE) {

                        header.y = (-height).toFloat()
                    }
                    updateHeader(data, title, mCurrentPosition)
                }
            }
        })
        updateHeader(data, title, mCurrentPosition)

        mBrandAdapter.onItemClickListener = BaseQuickAdapter.OnItemClickListener { _, _, position ->
            if (mBrandAdapter.data[position].itemType == BrandItem.TITLE)
                return@OnItemClickListener
            if (position > mBrandAdapter.data.size - 1) {
                return@OnItemClickListener
            }
            mBrandAdapter.data[mBrandPosition].choose = false
            mBrandAdapter.notifyItemChanged(mBrandPosition)
            mBrandAdapter.data[position].choose = true
            mBrandAdapter.notifyItemChanged(position)
            mBrandPosition = position
            mSearch.brandId = mBrandAdapter.data[position].brand?.brandId ?: 0
            mSearch.seriesId = null
            initSeriesData()
            BackHomeTimer.getInstance().resetTime()
        }


    }

    private fun initBrandData() {
        loadDialog.show()
        ApiFactory.getErpApi()
                .brand()
                .compose(Composers.handleError())
                .subscribeOn(Schedulers.io())
                .observeOn(Schedulers.computation())
                .map {
                    it.forEach {
                        val item = BrandItem(BrandItem.TITLE, it.initial, null)
                        data.add(item)
                        it.brandInfo?.forEach {
                            val brandItem = BrandItem(BrandItem.ITEM, it.brandInitial, it)
                            data.add(brandItem)
                        }
                    }
                    return@map data
                }
                .observeOn(AndroidSchedulers.mainThread())
                .subscribe({
                    it.add(0, BrandItem(itemType = BrandItem.TITLE, title = "所有品牌", item = null))
                    it.add(1, BrandItem(itemType = BrandItem.ITEM, title = "所有品牌", item = Brand(brandName = "所有品牌")))

                    if (mSearch.brandId != 0)
                        it.forEachIndexed { index, brandItem ->
                            if (brandItem.brand?.brandId == mSearch.brandId) {
                                brandItem.choose = true
                                mBrandPosition = index
                                return@forEachIndexed
                            }
                        }
                    mBrandAdapter.setNewData(it)
                    loadDialog.dismiss()
                }, {})
    }

    private fun updateHeader(data: ArrayList<BrandItem>, title: TextView?, mCurrentPosition: Int) {
        if (data.size == 0 || mCurrentPosition < 0 || data.size <= mCurrentPosition) {
            header.visibility = View.GONE
        } else {
            header.visibility = View.VISIBLE
            title?.text = data[mCurrentPosition].title
        }
    }

    override fun onTouchLetterChange(letter: String, isTouch: Boolean) {
        KLog.w("letter", letter + isTouch)
        if (isTouch) {
            mLetterText.visibility = View.VISIBLE
            mLetterText.text = letter
        } else {
            mLetterText.visibility = View.GONE
        }
        data.forEachIndexed { index, brandItem ->
            if (brandItem.itemType == BrandItem.TITLE) {
                if (brandItem.title == letter) {
                    mBrandManager.scrollToPositionWithOffset(index, 0)
                }
            }
        }
    }

    @SuppressLint("SetTextI18n")
    private fun initOther() {

        val mileageArray = resources.getStringArray(R.array.mileage_array)
        mileage_choose.setOnRangeSelectedListener { left, right ->
            mSearch.fromMileageIndex = left
            mSearch.toMileageIndex = right
            if (right == mileageArray.size - 1 && left == 0) {
                mileage.text = mileageArray[right]
                mSearch.fromMileage = null
                mSearch.toMileage = null
            } else if (right == mileageArray.size - 1 && left != 0) {
                mileage.text = mileageArray[left] + "万公里以上"
                mSearch.fromMileage = mileageArray[left].toInt()
                mSearch.toMileage = null
            } else if (right != mileageArray.size - 1 && left != 0) {
                mileage.text = mileageArray[left] + "~" + mileageArray[right] + "万公里"
                mSearch.fromMileage = mileageArray[left].toInt()
                mSearch.toMileage = mileageArray[right].toInt()
            } else if (right != mileageArray.size - 1 && left == 0) {
                mileage.text = mileageArray[right] + "万公里以内"
                mSearch.fromMileage = null
                mSearch.toMileage = mileageArray[right].toInt()
            }
        }

        val carAge = resources.getStringArray(R.array.car_age_array)

        car_age_choose.setOnRangeSelectedListener { left, right ->
            mSearch.fromCarAgeIndex = left
            mSearch.toCarAgeIndex = right
            if (right == carAge.size - 1 && left == 0) {
                car_age.text = carAge[right]
                mSearch.fromCarAge = null
                mSearch.toCarAge = null
            } else if (right == carAge.size - 1 && left != 0) {
                car_age.text = carAge[left] + "年以上"
                mSearch.fromCarAge = carAge[left].toInt()
                mSearch.toCarAge = null
            } else if (right != carAge.size - 1 && left != 0) {
                car_age.text = carAge[left] + "~" + carAge[right] + "年"
                mSearch.fromCarAge = carAge[left].toInt()
                mSearch.toCarAge = carAge[right].toInt()
            } else if (right != carAge.size - 1 && left == 0) {
                car_age.text = carAge[right] + "年以内"
                mSearch.fromCarAge = null
                mSearch.toCarAge = carAge[right].toInt()
            }
        }

        val priceArray = resources.getStringArray(R.array.price_array)


        price_rangeBar.setOnRangeSelectedListener { left, right ->
            mSearch.fromRetailPriceIndex = left
            mSearch.toRetailPriceIndex= right
            if (right == priceArray.size - 1 && left == 0) {
                price.text = priceArray[right]
                mSearch.fromRetailPrice = null
                mSearch.toRetailPrice = null
            } else if (right == priceArray.size - 1 && left != 0) {
                price.text = priceArray[left] + "万以上"
                mSearch.fromRetailPrice = priceArray[left].toDouble()
                mSearch.toRetailPrice = null
            } else if (right != priceArray.size - 1 && left != 0) {
                price.text = priceArray[left] + "~" + priceArray[right] + "万"
                mSearch.fromRetailPrice = priceArray[left].toDouble()
                mSearch.toRetailPrice = priceArray[right].toDouble()
            } else if (right != priceArray.size - 1 && left == 0) {
                price.text = priceArray[right] + "万以内"
                mSearch.fromRetailPrice = null
                mSearch.toRetailPrice = priceArray[right].toDouble()
            }
        }
    }
}